﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Esponce.QRCode;

namespace Esponce.Views
{
	public partial class LogView : UserControl
	{
		public LogView()
		{
			InitializeComponent();
			this.Loaded += (sender, e) => Navigate();
		}

		protected void Navigate()
		{
			var info = Application.GetResourceStream(new Uri("/Resources/log.html", UriKind.Relative));
			browser.NavigateToStream(info.Stream);
		}

		protected delegate void CrossThreadDelegate();

		public void WriteLine(string message, string css = null)
		{
			try
			{
				browser.InvokeScript("WriteLine", message, css);
			}
			catch
			{
				Dispatcher.BeginInvoke(new CrossThreadDelegate(() =>
				{
					try
					{
						browser.InvokeScript("WriteLine", message, css);
					}
					catch
					{
					}
				}), null);
			}
		}

		public void Clear()
		{
			try
			{
				browser.InvokeScript("Clear");
			}
			catch
			{
			}
		}

		public void Log(Exception ex)
		{
			try
			{
				var builder = new StringBuilder();

				var error = ex as WebException;
				var qrerror = ex as QRCodeException;

				if (qrerror != null)
				{
					builder.AppendFormat("{0} {1}", qrerror.StatusCode, qrerror.StatusDescription).AppendLine();
					builder.AppendFormat("Error {0}: {1}", qrerror.ErrorCode, qrerror.Message).AppendLine();
					if (!string.IsNullOrEmpty(qrerror.Hint))
					{
						builder.AppendLine("Hint: " + qrerror.Hint);
					}
				}
				else if (error != null)
				{
					builder.AppendLine(ex.Message);
					if (error.Response != null && error.Response.Headers != null)
					{
						string message = error.Response.Headers["X-Api-Error"];
						string code = error.Response.Headers["X-Api-Error-Code"];
						string hint = error.Response.Headers["X-Api-Error-Hint"];
						
						builder.AppendFormat("Error {0}: {1}", code, message).AppendLine();
						if (!string.IsNullOrEmpty(hint))
						{
							builder.AppendLine("Hint: " + hint);
						}
					}
				}
				else
				{
					builder.AppendLine(ex.Message);
				}

				string content = builder.ToString();
				WriteLine(content, "error");
			}
			catch (Exception error)
			{
				MessageBox.Show(error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
	}
}
